package com.infovalley.tx_plugin;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.tencent.connect.UnionInfo;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXMusicObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.DefaultUiListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.Registrar;

import static android.content.ContentResolver.SCHEME_FILE;

import androidx.annotation.NonNull;

/**
 * TxPlugin
 */
public class TxPlugin implements MethodCallHandler, PluginRegistry.ActivityResultListener, FlutterPlugin, ActivityAware {

    private static final String TAG = "Nick";

    //注册到微信
    private static final String REGISTER_WX = "register_wx";
    //是否安装了微信
    private static final String IS_INSTALLED_WX = "is_installed_wx";

    //微信授权
    private static final String AUTHORIZATION_WX = "authorization_wx";

    //分享
    private static final String SHARE_TEXT_WX = "share_text_wx";
    private static final String SHARE_IMAGE_WX = "share_image_wx";
    private static final String SHARE_MUSIC_WX = "share_music_wx";
    private static final String SHARE_VIDEO_WX = "share_video_wx";
    private static final String SHARE_WEB_PAGE_WX = "share_web_page_wx";
    private static final String SHARE_MINI_PROGRAM_WX = "share_mini_program_wx";

    //微信支付
    private static final String PAY_WX = "pay_wx";

    //第三方app和微信通信的openApi接口
    private IWXAPI api;

    static MethodChannel myMethodChannel;
    @SuppressLint("StaticFieldLeak")
    private static Context txContext;
    @SuppressLint("StaticFieldLeak")
    private static final TxPlugin txPlugin = new TxPlugin();
    @SuppressLint("StaticFieldLeak")
    private static Activity activity;
    private ActivityPluginBinding activityPluginBinding;

    //缩略图的大小
    private static final int THUMB_SIZE = 150;

    //注册到微信SDK的监听
    static BroadcastReceiver wxRegisterBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (PluginConstants.getWxApi() != null) {
                PluginConstants.getWxApi().registerApp(PluginConstants.getWxAppID());
            }
        }
    };

    //微信授权的回调
    static BroadcastReceiver wxAuthorizationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getStringExtra("code");
            Map<String, Object> map = new HashMap<>();
            map.put("code", code);
            myMethodChannel.invokeMethod("onWxAuthResponse", map);
        }
    };
    //微信分享的回调
    static BroadcastReceiver wxSharedBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int errCode = intent.getIntExtra("errCode", -1);
            Map<String, Object> map = new HashMap<>();
            map.put("errCode", errCode);
            myMethodChannel.invokeMethod("onWxShareResponse", map);
        }
    };
    //微信支付的回调
    static BroadcastReceiver wxPayBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            int errCode = intent.getIntExtra("errCode", -3);
            String errStr = intent.getStringExtra("errStr");
            String transaction = intent.getStringExtra("transaction");
            String openId = intent.getStringExtra("openId");

            Log.d(TAG, "支付返回的结果---errCode:" + errCode);
            Log.d(TAG, "支付返回的结果---errStr:" + errStr);
            Log.d(TAG, "支付返回的结果---transaction:" + transaction);
            Log.d(TAG, "支付返回的结果---openId:" + openId);
            Map<String, Object> map = new HashMap<>();
            map.put("errCode", errCode);
            map.put("errStr", errStr);
            map.put("transaction", transaction);
            map.put("openId", openId);
            myMethodChannel.invokeMethod("onWxPayResponse", map);
        }
    };

    //微信h5跳转app的回调
    static BroadcastReceiver wxJumpAppBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String extra = intent.getStringExtra(PluginConstants.EXTINFO);
            Log.d(TAG, "跳转app---extInfo:" + extra);
            myMethodChannel.invokeMethod("h5WxLaunchApp", extra);
        }
    };



    // QQ注册
    private static final String REGISTER_QQ = "register_qq";
    //QQ授权
    private static final String AUTHORIZATION_QQ = "authorization_QQ";
    //QQ unionid
    private static final String UNIONID_QQ = "unionid_QQ";
    //是否安装QQ
    private static final String IS_INSTALLED_QQ = "is_installed_qq";
    //退出QQ登录
    private static final String LOGOUT_QQ = "logout_qq";
    //获取用户信息
    private static final String GET_USER_INFO_QQ = "get_user_info_qq";
    //分享文本到QQ
    private static final String SHARE_TEXT_QQ = "share_text_qq";
    //分享图片到QQ
    private static final String SHARE_IMAGE_QQ = "share_image_qq";
    //分享音乐到QQ
    private static final String SHARE_MUSIC_QQ = "share_music_qq";
    //分享网页到QQ
    private static final String SHARE_WEB_PAGE_QQ = "share_web_page_qq";

    private static final String ARGUMENT_KEY_RESULT_OPENID = "openid";
    private static final String ARGUMENT_KEY_RESULT_ACCESS_TOKEN = "access_token";

    private Tencent tencent;

    /// 3.5.7版本新增接口提供用户设置是否已授权获取设备信息，在调用互联SDK相关功能接口之前，需要应用在确认用户已授权应用获取设备信息后，调用下面代码通知 SDK：
    //Tencent.setIsPermissionGranted(true);
    //如果未调用该接口或传参为false时，调用其它功能接口将直接返回失败。
    //3.5.9版本中可以调用Tencent.setisPermissionGranted(true, Build.Model)传入Build.Model，传入后SDK内部不再自行获取。

    // 腾讯QQ-用户设置是否已授权获取设备信息
    private static final String QQ_IS_AUTH_GET_DEVICE_INFO = "qq_is_auth_get_device_info";

    //qq登录的监听
    private final IUiListener qqAuthorizationListener = new DefaultUiListener() {
        @Override
        public void onComplete(Object o) {
            Log.d(TAG, "QQ---onComplete" + o.toString());
            Map<String, Object> map = new HashMap<>();
            try {
                if (o instanceof JSONObject) {
                    JSONObject object = (JSONObject) o;
                    int ret = !object.isNull("ret") ? object.getInt("ret") : -1;
                    if (ret == 0) {
                        String openId = !object.isNull(ARGUMENT_KEY_RESULT_OPENID) ? object.getString(ARGUMENT_KEY_RESULT_OPENID) : "";
                        String accessToken = !object.isNull(ARGUMENT_KEY_RESULT_ACCESS_TOKEN) ? object.getString(ARGUMENT_KEY_RESULT_ACCESS_TOKEN) : "";
                        String expires = !object.isNull(Constants.PARAM_EXPIRES_IN) ? object.getString(Constants.PARAM_EXPIRES_IN) : "";
                        if (!TextUtils.isEmpty(openId) && !TextUtils.isEmpty(accessToken)) {
                            map.put("errCode", 0);
                            map.put("openID", openId);
                            map.put("accessToken", accessToken);

                            tencent.setAccessToken(accessToken, expires);
                            tencent.setOpenId(openId);
                        } else {
                            map.put("errCode", -1);
                        }

                        Log.d(TAG, "");

                    } else {
                        map.put("errCode", -1);
                    }
                }
            } catch (JSONException e) {
                map.put("errCode", -1);
            }
            myMethodChannel.invokeMethod("onQQAuthResponse", map);
        }

        @Override
        public void onError(UiError uiError) {
            Log.d(TAG, "QQ---onError" + uiError.errorCode);
            Log.d(TAG, "QQ---onError" + uiError.errorDetail);
            Log.d(TAG, "QQ---onError" + uiError.errorMessage);
        }

        @Override
        public void onCancel() {
            Log.d(TAG, "QQ---onCancel");
        }
    };

    /// 获取qq unionid
    private final IUiListener getQQUnionidlistener = new DefaultUiListener() {
        @Override
        public void onError(UiError e) {
            Log.d(TAG, "QQ---onError" + e.errorCode);
        }

        @Override
        public void onComplete(final Object response) {
            if(response != null){
                JSONObject jsonObject = (JSONObject)response;
                try {
                    String unionid = jsonObject.getString("unionid");
//                    map.put("unionid", unionid);
                    myMethodChannel.invokeMethod("onQQGetUnionid", unionid);

                } catch (Exception e){
                    Log.d(TAG, "QQ---onComplete--no unionid");
                }
            }else {
                Log.d(TAG, "QQ---onComplete--no unionid");
            }
        }

        @Override
        public void onCancel() {
            Log.d(TAG, "QQ---onCancel");
        }
    };

    //qq分享的监听
    private final IUiListener qqSharedListener = new DefaultUiListener() {
        @Override
        public void onComplete(Object response) {

            Log.d(TAG, "qq分享的监听---onComplete---" + response.toString());
            Map<String, Object> map = new HashMap<>();
            try {
                if (response instanceof JSONObject) {
                    JSONObject object = (JSONObject) response;
                    int ret = !object.isNull("ret") ? object.getInt("ret") : -1;
                    map.put("errCode", ret);
                }
            } catch (JSONException e) {
                map.put("errCode", -1);
                Log.d(TAG, "qq分享的监听---" + e.getMessage());
            }
            myMethodChannel.invokeMethod("onQQShareResponse", map);
        }

        @Override
        public void onError(UiError uiError) {
            Log.d(TAG, "qq分享的监听---onError" + uiError.errorCode);
            Log.d(TAG, "qq分享的监听---onError" + uiError.errorDetail);
            Log.d(TAG, "qq分享的监听---onError" + uiError.errorMessage);
        }

        @Override
        public void onCancel() {
            Log.d(TAG, "qq分享的监听---onCancel");
        }
    };



    /**
     * Plugin registration.
     */
    public static void registerWith(Registrar registrar) {
        Log.d(TAG, "registerWith");

        myMethodChannel = new MethodChannel(registrar.messenger(), "tencent_plugin");
        txContext = registrar.context();
        activity = registrar.activity();

        //微信支付的监听
        txContext.registerReceiver(wxPayBroadcastReceiver,
                new IntentFilter(PluginConstants.WX_PAY_FILTER));

        //微信授权的回调监听
        txContext.registerReceiver(wxAuthorizationBroadcastReceiver,
                new IntentFilter(PluginConstants.WX_AUTHORIZATION_FILTER));

        //微信分享的回调监听
        txContext.registerReceiver(wxSharedBroadcastReceiver,
                new IntentFilter(PluginConstants.WX_SHARED_FILTER));

        //微信h5跳转app回调监听
        txContext.registerReceiver(wxJumpAppBroadcastReceiver,
                new IntentFilter(PluginConstants.WX_JUMPAPP_MESSAGE));

        registrar.addActivityResultListener(txPlugin);
        myMethodChannel.setMethodCallHandler(txPlugin);


    }

    /// ActivityAware
    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        Log.d(TAG, "onAttachedToEngine");

        myMethodChannel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "tencent_plugin");
        txContext = flutterPluginBinding.getApplicationContext();
        
        //微信支付的监听
        txContext.registerReceiver(wxPayBroadcastReceiver,
                new IntentFilter(PluginConstants.WX_PAY_FILTER));

        //微信授权的回调监听
        txContext.registerReceiver(wxAuthorizationBroadcastReceiver,
                new IntentFilter(PluginConstants.WX_AUTHORIZATION_FILTER));

        //微信分享的回调监听
        txContext.registerReceiver(wxSharedBroadcastReceiver,
                new IntentFilter(PluginConstants.WX_SHARED_FILTER));

        //微信h5跳转app回调监听
        txContext.registerReceiver(wxJumpAppBroadcastReceiver,
                new IntentFilter(PluginConstants.WX_JUMPAPP_MESSAGE));

        myMethodChannel.setMethodCallHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        Log.d(TAG, "onDetachedFromEngine");
    }

    /// ActivityAware
    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) {
        Log.d(TAG, "onAttachedToActivity");
        activity = activityPluginBinding.getActivity();
        this.activityPluginBinding = activityPluginBinding;
        activityPluginBinding.addActivityResultListener(this);
    }

    @Override
    public void onDetachedFromActivity() {
        Log.d(TAG, "onDetachedFromActivity");
        this.activityPluginBinding.removeActivityResultListener(this);
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {
        Log.d(TAG, "onDetachedFromActivityForConfigChanges");
    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding activityPluginBinding) {
        Log.d(TAG, "onReattachedToActivityForConfigChanges");
    }

    @Override
    public void onMethodCall(MethodCall call, @NonNull Result result) {
        switch (call.method) {
            case REGISTER_WX:
                //注册到微信
                registerToWx(call, result);
                break;
            case IS_INSTALLED_WX:
                //注册到微信
                isInstalledWx(result);
                break;
            case AUTHORIZATION_WX:
                //微信授权
                authorizationByWx(call, result);
                break;
            case SHARE_TEXT_WX:
                shareTextToWx(call);
                break;
            case SHARE_IMAGE_WX:
                shareImageToWx(call);
                break;
            case SHARE_MUSIC_WX:
                shareMusicToWx(call);
                break;
            case SHARE_VIDEO_WX:
                shareVideoToWx(call);
                break;
            case SHARE_WEB_PAGE_WX:
                shareWebPageToWx(call);
                break;
            case SHARE_MINI_PROGRAM_WX:
                shareMiniProgramToWx(call, result);
                break;
            case PAY_WX:
                payWX(call);
                break;
            case QQ_IS_AUTH_GET_DEVICE_INFO:
                qqAuthGetDeviceInfo(call, result);
                break;
            case REGISTER_QQ:
                registerQQ(call, result);
            case AUTHORIZATION_QQ:
                authorizationByQQ(call, result);
                break;
            case UNIONID_QQ:
                getQQUnionid(result);
                break;
            case IS_INSTALLED_QQ:
                isInstalledQQ(result);
                break;
            case LOGOUT_QQ:
                logoutQQ(result);
                break;
            case GET_USER_INFO_QQ:
                getUserInfoQQ();
                break;
            case SHARE_TEXT_QQ:
                shareTextToQQ(call);
                break;
            case SHARE_IMAGE_QQ:
                shareImageToQQ(call);
                break;
            case SHARE_MUSIC_QQ:
                shareMusicToQQ(call);
                break;
            case SHARE_WEB_PAGE_QQ:
                shareWebPageToQQ(call);
                break;

            case "getPlatformVersion":
                result.success("Android " + android.os.Build.VERSION.RELEASE);
                break;
            default:
                result.notImplemented();
                break;

        }
    }


    //注册到微信
    private void registerToWx(MethodCall call, Result result) {
        String wxAppId = call.argument("appid");
        PluginConstants.setWxAppID(wxAppId);

        api = WXAPIFactory.createWXAPI(txContext, wxAppId);
        boolean resultState = api.registerApp(wxAppId);
        PluginConstants.setWxApi(api);

        //建议动态监听微信启动广播进行注册到微信
        txContext.registerReceiver(wxRegisterBroadcastReceiver,
                new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));

        result.success(resultState);
    }

    //微信是否安装
    private void isInstalledWx(Result result) {
        final PackageManager packageManager = txContext.getPackageManager();

        boolean flag;
        PackageInfo info;
        try {
            info = packageManager.getPackageInfo("com.tencent.mm", PackageManager.GET_SIGNATURES);
            Log.d(TAG, "是否安装了WX" + (info != null));
            flag = (info != null);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            flag = false;
        }
        result.success(flag);
    }

    //通过微信授权
    private void authorizationByWx(MethodCall call, Result result) {
        Log.d(TAG, "通过微信授权");
        String scope = call.argument("scope");
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = scope;
        req.state = "wx_sdk_info_valley";
        boolean resultState = api.sendReq(req);
        result.success(resultState);
    }

    //分享文本到微信
    private void shareTextToWx(final MethodCall call) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "分享文本到微信好友");
                String text = call.argument("text");
                String mTargetScene = call.argument("targetScene");

                //初始化一个 WXTextObject 对象，填写分享的文本内容
                WXTextObject textObj = new WXTextObject();
                textObj.text = text;

                //用 WXTextObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = textObj;
                msg.description = text;

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("text");
                req.message = msg;
                req.scene = PluginUtils.parseInt(mTargetScene, 0);
                //调用api接口，发送数据到微信
                api.sendReq(req);
            }
        }).start();
    }

    //分享图片到微信
    private void shareImageToWx(final MethodCall call) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "分享图片到微信");
                final String imageUrl = call.argument("imageUrl");
                final String mTargetScene = call.argument("targetScene");
                final byte[] imageData = call.argument("imageData");

                WXMediaMessage msg = new WXMediaMessage();

                Bitmap bmp;

                try {
                    if (imageData != null) {
                        bmp = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                    } else {
                        bmp = BitmapFactory.decodeStream(new URL(imageUrl).openStream());
                    }

                    WXImageObject imageObject = new WXImageObject(bmp);
                    Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);

                    msg.mediaObject = imageObject;
                    bmp.recycle();
                    msg.thumbData = PluginUtils.bmpToByteArray(thumbBmp, true);

                } catch (Exception e) {
                    e.printStackTrace();
                }


                //构造一个Req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("img");
                req.message = msg;
                req.scene = PluginUtils.parseInt(mTargetScene, 0);
                //调用api接口，发送数据到微信
                api.sendReq(req);
            }
        }).start();
    }

    //分享音乐到微信
    private void shareMusicToWx(final MethodCall call) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "分享音乐到微信");
                ///音乐的URL地址
                String musicUrl = call.argument("musicUrl");
                //音乐标题
                String musicTitle = call.argument("musicTitle");
                //音乐描述
                String musicDescription = call.argument("musicDescription");
                //好友还是朋友圈
                String mTargetScene = call.argument("targetScene");

                //初始化一个WXMusicObject，填写url
                WXMusicObject music = new WXMusicObject();
                music.musicUrl = musicUrl;

                //用 WXMusicObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = music;
                msg.title = musicTitle;
                msg.description = musicDescription;

                Bitmap bmp;
                try {
                    bmp = BitmapFactory.decodeStream(new URL(musicUrl).openStream());
                    Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                    //设置音乐缩略图
                    msg.thumbData = PluginUtils.bmpToByteArray(thumbBmp, true);
                } catch (IOException e) {
                    e.printStackTrace();
                }


                //构造一个Req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("music");
                req.message = msg;
                req.scene = PluginUtils.parseInt(mTargetScene, 0);
                //调用api接口，发送数据到微信
                api.sendReq(req);
            }
        }).start();
    }

    //分享视频到微信
    private void shareVideoToWx(final MethodCall call) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "分享视频到微信");
                ///视频的URL地址
                String videoUrl = call.argument("videoUrl");
                //视频标题
                String videoTitle = call.argument("videoTitle");
                //视频描述
                String videoDescription = call.argument("videoDescription");
                //好友还是朋友圈
                String mTargetScene = call.argument("targetScene");


                //初始化一个WXVideoObject，填写url
                WXVideoObject video = new WXVideoObject();
                video.videoUrl = videoUrl;

                //用WXVideoObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage(video);
                msg.title = videoTitle;
                msg.description = videoDescription;

                Bitmap bmp;
                try {
                    bmp = BitmapFactory.decodeStream(new URL(videoUrl).openStream());
                    Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                    //设置视频缩略图
                    msg.thumbData = PluginUtils.bmpToByteArray(thumbBmp, true);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //构造一个Req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("video");
                req.message = msg;
                req.scene = PluginUtils.parseInt(mTargetScene, 0);

                //调用api接口，发送数据到微信
                //调用api接口，发送数据到微信
                api.sendReq(req);
            }
        }).start();
    }

    //分享网页到微信
    private void shareWebPageToWx(final MethodCall call) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "分享网页到微信");
                ///网页的URL地址
                String webPageUrl = call.argument("webPageUrl");
                //网页标题
                String webPageTitle = call.argument("webPageTitle");
                //网页描述
                String webPageDescription = call.argument("webPageDescription");
                //好友还是朋友圈
                String mTargetScene = call.argument("targetScene");
                ///缩略图
                String thumbnail=call.argument("thumbnail");
                /// 图片缩略图数据
                byte[] imageData = call.argument("imageData");

                //初始化一个WXWebPageObject，填写url
                WXWebpageObject webPage = new WXWebpageObject();
                webPage.webpageUrl = webPageUrl;

                //用 WXWebPageObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage(webPage);
                msg.title = webPageTitle;
                msg.description = webPageDescription;

                Bitmap bmp;
                try {
                    byte[] tempImageData;
                    if (imageData != null) {
                        tempImageData = imageData;
                    } else {
                        bmp = BitmapFactory.decodeStream(new URL(thumbnail).openStream());
                        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                        tempImageData = PluginUtils.bmpToByteArray(thumbBmp, true);
                    }
                    msg.thumbData = tempImageData;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                
                //构造一个Req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                req.scene = PluginUtils.parseInt(mTargetScene, 0);

                //调用api接口，发送数据到微信
                api.sendReq(req);
            }
        }).start();

    }

    //分享小程序到微信
    private void shareMiniProgramToWx(final MethodCall call, final Result result) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "分享小程序到微信");

                ///小程序封面图片的URL地址
                String miniProgramUrl = call.argument("miniProgramWebPageUrl");
                //小程序消息title
                String miniProgramTitle = call.argument("miniProgramWebPageTitle");
                //小程序消息desc
                String miniProgramDescription = call.argument("miniProgramWebPageDescription");
                //小程序原始id
                String userName = call.argument("miniProgramId");
                // 小程序路径
                String miniProgramPath = call.argument("miniProgramPath");

                WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
                // 兼容低版本的网页链接
                miniProgramObj.webpageUrl = miniProgramUrl;

                // 正式版:0，测试版:1，体验版:2
                miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;
                // 小程序原始id
                miniProgramObj.userName = userName;
                //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
                miniProgramObj.path = miniProgramPath;
                WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
                msg.title = miniProgramTitle;
                msg.description = miniProgramDescription;

                Bitmap bmp;
                try {
                    bmp = BitmapFactory.decodeStream(new URL(miniProgramUrl).openStream());
                    Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                    // // 小程序消息封面图片，小于128k
                    msg.thumbData = PluginUtils.bmpToByteArray(thumbBmp, true);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //构造一个Req
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("miniProgram");
                req.message = msg;

                // 目前只支持会话
                req.scene = SendMessageToWX.Req.WXSceneSession;

                //调用api接口，发送数据到微信
                boolean resultState = api.sendReq(req);
                result.success(resultState);
            }
        }).start();
    }

    //微信支付
    private void payWX(MethodCall call) {

        String appId = call.argument("appid");
        //微信支付分配的商户号
        String partnerId = call.argument("partnerid");
        //预支付交易会话ID
        String prepayId = call.argument("prepayid");
        //随机字符串
        String nonceStr = call.argument("noncestr");
        //时间戳
        String timeStamp = call.argument("timestamp");
        //暂填写固定值"Sign=WXPay"
        String packageValue = call.argument("package");
        //签名
        String sign = call.argument("sign");

        Log.d(TAG, "payWX---appId---" + appId);
        Log.d(TAG, "payWX---partnerId---" + partnerId);
        Log.d(TAG, "payWX---prepayId---" + prepayId);
        Log.d(TAG, "payWX---nonceStr---" + nonceStr);
        Log.d(TAG, "payWX---timeStamp---" + timeStamp);
        Log.d(TAG, "payWX---sign---" + sign);
        Log.d(TAG, "payWX---packageValue---" + packageValue);

        PayReq req = new PayReq();
        req.appId = appId;
        req.partnerId = partnerId;
        req.prepayId = prepayId;
        req.nonceStr = nonceStr;
        req.timeStamp = timeStamp;
        req.packageValue = packageValue;
        req.sign = sign;
        req.extData = "app data"; // optional

        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        api.sendReq(req);
    }

    //对应该请求的事务ID
    private String buildTransaction(String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) :
                type + System.currentTimeMillis();
    }

    // QQ - 用户是否授权获取设备信息
    private void qqAuthGetDeviceInfo(MethodCall call, Result result) {
        Log.d(TAG, "QQ授权true---qqAuthGetDeviceInfo");
        Tencent.setIsPermissionGranted(true);
        result.success(true);
    }


    // QQ注册
    private void registerQQ(MethodCall call, Result result) {
        Log.d(TAG, "QQ注册---registerQQ");
        String qqAppId = call.argument("appId");
        Log.d(TAG, "QQ注册---registerQQ == " + qqAppId);
        result.success(true);
    }

    //QQ授权
    private void authorizationByQQ(MethodCall call, Result result) {
        Log.d(TAG, "QQ授权---authorizationByQQ");
        if (tencent == null) {
            tencent = Tencent.createInstance(PluginConstants.getQqAppID(), activity);
        }
        String scope = call.argument("scope");

        boolean state = false;
        if (testQQInstall()) {
            state = true;
            int value = tencent.login(activity, scope, qqAuthorizationListener);
            Log.d(TAG, "QQ授权的结果---" + value);
        }
        result.success(state);
    }

    // 获取QQunionid
    private void getQQUnionid(Result result) {
        boolean state = false;
        if (testQQInstall()) {
            state = true;
            if (tencent != null && tencent.isSessionValid()) {
                UnionInfo unionInfo = new UnionInfo(txContext, tencent.getQQToken());
                unionInfo.getUnionId(getQQUnionidlistener);
            } else {
                Log.d(TAG, "QQ---onError - please login frist");
            }
        }
        result.success(state);
    }

    //QQ是否安装
    private void isInstalledQQ(Result result) {
        result.success(testQQInstall());
    }

    //本地方法---QQ是否安装
    private boolean testQQInstall() {
        final PackageManager packageManager = txContext.getPackageManager();
        boolean flag;
        PackageInfo info;
        try {
            info = packageManager.getPackageInfo("com.tencent.mobileqq",
                    PackageManager.GET_SIGNATURES);

            flag = (info != null);
            Log.d(TAG, "是否安装了QQ---" + flag);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    //退出QQ
    private void logoutQQ(Result result) {
        tencent.logout(txContext);
        result.success(true);
    }

    //获取QQ用户资料信息
    private void getUserInfoQQ() {
        Log.d("nick", "getUserInfoQQ---android not api");
    }


    /**
     * 分享图文到QQ和QQ空间
     * String targetScene QQ好友(Friend)/QQ空间
     * String title 标题
     * String summary 摘要
     * String targetUrl 连接的地址
     * String imageUri 图片的链接
     * String appName App名称
     */
    private void shareTextToQQ(final MethodCall call) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String friendState = call.argument("targetScene");
                //要分享的标题
                String title = call.argument("title");
                //要分享的摘要
                String summary = call.argument("summary");
                String targetUrl = call.argument("targetUrl");
                ArrayList<String> imageUriList = call.argument("imageUri");
                String appName = call.argument("appName");

                final Bundle params = new Bundle();

                if ("Friend".equals(friendState)) {
                    //分享给QQ好友
                    Log.d(TAG, "分享给QQ好友");
                    params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                    params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
                    params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
                    params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, targetUrl);
                    assert imageUriList != null;
                    params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageUriList.get(0));
                    params.putString(QQShare.SHARE_TO_QQ_APP_NAME, appName);
                    params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
                    if (tencent == null) {
                        tencent = Tencent.createInstance(PluginConstants.getQqAppID(), activity);
                    }
                    tencent.shareToQQ(activity, params, qqSharedListener);
                } else {
                    //分享到QQ空间
                    Log.d(TAG, "分享到QQ空间");
                    params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_NO_TYPE);
                    params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);//必填
                    params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);//选填
                    params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, targetUrl);//必填
                    params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUriList);
                    if (tencent == null) {
                        tencent = Tencent.createInstance(PluginConstants.getQqAppID(), activity);
                    }
                    tencent.shareToQzone(activity, params, qqSharedListener);
                }
            }
        }).start();
    }

    /**
     * 分享纯图片---只支持QQ
     * String  targetScene QQ好友(Friend)/QQ空间
     * String  imageUri 图片的路径
     * String  appName 应用名称
     */
    private void shareImageToQQ(final MethodCall call) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                String scene = call.argument("targetScene");
                String imageUri = call.argument("imageUri");
                String appName = call.argument("appName");

                byte[] imageData = call.argument("imageData");
                Log.d(TAG, "分享纯图片到QQ");

                File imageDataFile;
                if (imageData != null) {

                    imageUri = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + System.currentTimeMillis() + ".png";

                    Log.d(TAG, "r分享纯图片到QQ---picture path-" + imageUri);
                    imageDataFile = new File(imageUri);
                    Bitmap bm = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);

                    try {
                        FileOutputStream fos = new FileOutputStream(imageDataFile);
                        bm.compress(Bitmap.CompressFormat.PNG, 90, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //增加纯图分享图片不能大于5M的限制：
                    imageDataFile = new File(imageUri);
                }
                if (imageDataFile.length() >= 5 * 1024 * 1024) {
                    Log.d(TAG, "doShareImageToQQ is error picture size over 100MB");
                    return;
                }

                Bundle params = new Bundle();
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imageUri);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, appName);
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
                if (!"Friend".equals(scene)) {
                    params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
                }
                if (tencent == null) {
                    tencent = Tencent.createInstance(PluginConstants.getQqAppID(), activity);
                }
                tencent.shareToQQ(activity, params, qqSharedListener);
            }
        }).start();

    }

    /**
     * 分享音乐---支持QQ
     * String targetScene QQ好友(Friend)/QQ空间
     * String title 标题
     * String summary 摘要
     * String imageUri 图片的链接
     * String targetUrl 连接的地址
     * String musicUrl 音乐的地址
     * String appName App名称
     */
    private void shareMusicToQQ(final MethodCall call) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String scene = call.argument("targetScene");
                String title = call.argument("title");
                String summary = call.argument("summary");
                String imageUri = call.argument("imageUri");
                String targetUrl = call.argument("targetUrl");
                String musicUrl = call.argument("musicUrl");
                String appName = call.argument("appName");

                if ("Friend".equals(scene)) {
                    Log.d(TAG, "分享音乐到QQ");
                    final Bundle params = new Bundle();
                    params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_AUDIO);
                    params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
                    params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
                    params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, targetUrl);
                    params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageUri);
                    params.putString(QQShare.SHARE_TO_QQ_AUDIO_URL, musicUrl);
                    params.putString(QQShare.SHARE_TO_QQ_APP_NAME, appName);
                    params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
                    if (tencent == null) {
                        tencent = Tencent.createInstance(PluginConstants.getQqAppID(), activity);
                    }
                    tencent.shareToQQ(activity, params, qqSharedListener);
                }
            }
        }).start();


    }

    /**
     * 分享网页---支持QQ/QZone
     * String targetScene QQ好友(Friend)/QQ空间
     * String title 标题
     * String summary 摘要
     * String imageUri 图片的路径
     * String targetUrl 连接的地址
     * String appName App名称
     */
    private void shareWebPageToQQ(final MethodCall call) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String scene = call.argument("targetScene");
                String title = call.argument("title");
                String summary = call.argument("summary");
                String networkImageUrl = call.argument("networkImageUrl");
                String targetUrl = call.argument("targetUrl");
                String appName = call.argument("appName");

                Bundle params = new Bundle();
                if ("Friend".equals(scene)) {
                    Log.d(TAG, "分享网页到QQ");
                    params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                    params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
                    if (!TextUtils.isEmpty(summary)) {
                        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
                    }
                    if (!TextUtils.isEmpty(networkImageUrl)) {
                        Uri uri = Uri.parse(networkImageUrl);
                        if (TextUtils.equals(SCHEME_FILE, uri.getScheme())) {
                            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, uri.getPath());
                        } else {
                            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, networkImageUrl);
                        }
                    }
                    params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, targetUrl);
                    if (!TextUtils.isEmpty(appName)) {
                        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, appName);
                    }
                    if (tencent == null) {
                        tencent = Tencent.createInstance(PluginConstants.getQqAppID(), activity);
                    }
                    tencent.shareToQQ(activity, params, qqSharedListener);
                } else {
                    Log.d(TAG, "分享网页到QZone");
                    params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
                    params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
                    if (!TextUtils.isEmpty(summary)) {
                        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);
                    }
                    ArrayList<String> uris = new ArrayList<>();
                    if (!TextUtils.isEmpty(networkImageUrl)) {
                        Uri uri = Uri.parse(networkImageUrl);
                        if (TextUtils.equals(SCHEME_FILE, uri.getScheme())) {
                            uris.add(uri.getPath());
                        } else {
                            uris.add(networkImageUrl);
                        }
                    }
                    params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, uris);
                    params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, targetUrl);
                    if (tencent == null) {
                        tencent = Tencent.createInstance(PluginConstants.getQqAppID(), activity);
                    }
                    tencent.shareToQzone(activity, params, qqSharedListener);
                }
            }
        }).start();
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent intent) {
        Log.d(TAG, "onActivityResult---" + resultCode);

        switch (requestCode) {
            case Constants.REQUEST_API:
                Log.d(TAG, "REQUEST_API");
                break;
            case Constants.REQUEST_LOGIN:
                Log.d(TAG, "REQUEST_LOGIN");
                return Tencent.onActivityResultData(requestCode, resultCode, intent, qqAuthorizationListener);
            case Constants.REQUEST_QQ_SHARE:
            case Constants.REQUEST_QZONE_SHARE:
                Log.d(TAG, "REQUEST_QQ_SHARE---REQUEST_QZONE_SHARE");
                return Tencent.onActivityResultData(requestCode, resultCode, intent, qqSharedListener);
            case Constants.REQUEST_QQ_FAVORITES:
                Log.d(TAG, "REQUEST_QQ_FAVORITES");
                break;
            case Constants.REQUEST_SEND_TO_MY_COMPUTER:
                Log.d(TAG, "REQUEST_SEND_TO_MY_COMPUTER");
                break;
            case Constants.REQUEST_SHARE_TO_TROOP_BAR:
                Log.d(TAG, "REQUEST_SHARE_TO_TROOP_BAR");
                break;
            default:
                Log.d(TAG, "default");
                break;
        }
        return false;
    }
}
